<template>
  <div class="container">
    <h1>API测试</h1>

    <div class="api-config">
      <h2>API配置</h2>
      <div class="input-group">
        <label>API URL:</label>
        <input type="text" v-model="apiUrl" class="api-input" />
      </div>
      <div class="input-group">
        <label>内容类型:</label>
        <select v-model="contentType" class="api-input">
          <option value="json">JSON</option>
          <option value="form">Form URL-Encoded</option>
          <option value="multipart">Multipart Form Data</option>
        </select>
      </div>
      <div class="input-group">
        <label>超时时间(ms):</label>
        <input type="number" v-model="timeout" class="timeout-input" />
      </div>
    </div>
    
    <div class="card" v-if="contentType === 'json'">
      <h2>JSON数据</h2>
      <textarea v-model="jsonData" rows="15" class="json-input"></textarea>
    </div>
    
    <div class="card" v-else>
      <h2>表单数据</h2>
      <div class="form-fields">
        <div v-for="(field, index) in formFields" :key="index" class="form-field">
          <input v-model="field.key" placeholder="字段名" class="field-key" />
          <input v-model="field.value" placeholder="值" class="field-value" />
          <button @click="removeField(index)" class="btn small-btn danger">X</button>
        </div>
        <button @click="addField()" class="btn small-btn primary">+ 添加字段</button>
      </div>
    </div>
    
    <div class="preset-section">
      <h2>快速请求模板</h2>
      <div class="preset-buttons">
        <button @click="loadPreset('seats')" class="btn preset">添加座位数据</button>
        <button @click="loadPreset('login')" class="btn preset">用户登录</button>
        <button @click="loadPreset('createUser')" class="btn preset">创建用户</button>
        <button @click="loadPreset('createOrder')" class="btn preset">创建上机订单</button>
        <button @click="loadPreset('deplane')" class="btn preset">下机</button>
      </div>
    </div>
    
    <div class="controls">
      <button @click="testApi('post')" class="btn primary">测试 POST 请求</button>
      <button @click="testApi('get')" class="btn secondary">测试 GET 请求</button>
      <button @click="resetData" class="btn reset">重置数据</button>
    </div>
    
    <div class="card result" v-if="apiResult">
      <h2>API响应</h2>
      <div class="status" :class="{ success: apiSuccess, error: !apiSuccess }">
        状态: {{ apiSuccess ? '成功' : '失败' }}
      </div>
      <pre class="response">{{ apiResult }}</pre>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

const defaultData = [
  {
    "id": 1,
    "seat_id": 0,
    "item_name": "a11",
    "status": 2,
    "row_position": 2,
    "col_position": 3,
    "floor": 1,
    "module_type": 0,
    "region_id": 1
  },
  {
    "id": 2,
    "seat_id": 0,
    "item_name": "a11",
    "status": 1,
    "row_position": 2,
    "col_position": 4,
    "floor": 1,
    "module_type": 0,
    "region_id": 2
  },
  {
    "seat_id": 0,
    "item_name": "座位6914",
    "status": 2,
    "row_position": 2,
    "col_position": 2,
    "floor": 1,
    "module_type": 0,
    "region_id": 1
  }
];

const presets = {
  seats: {
    url: 'http://localhost:9001/internet/addEquipment',
    type: 'json',
    data: defaultData
  },
  login: {
    url: 'http://localhost:9001/user/login',
    type: 'form',
    data: [
      { key: 'phone', value: '123456789' },
      { key: 'cipher', value: '123456' }
    ]
  },
  createUser: {
    url: 'http://localhost:9001/user/createUser',
    type: 'form',
    data: [
      { key: 'name', value: '测试用户' },
      { key: 'phone', value: '13800138000' },
      { key: 'cipher', value: '123456' },
      { key: 'id_number', value: '110101199001011234' },
      { key: 'balance', value: '100' }
    ]
  },
  createOrder: {
    url: 'http://localhost:9001/order/createInternetOrder',
    type: 'form',
    data: [
      { key: 'number', value: '1' },
      { key: 'eq_id', value: '1' },
      { key: 'start_time', value: new Date().toISOString() },
      { key: 'state', value: '0' },
      { key: 'favorable_id', value: '4011' }
    ]
  },
  deplane: {
    url: 'http://localhost:9001/order/deplane',
    type: 'form',
    data: [
      { key: 'order_id', value: 'Ord_123456' },
      { key: 'end_time', value: new Date().toISOString() },
      { key: 'text', value: '网费' },
      { key: 'favorable_id', value: '4011' }
    ]
  }
};

export default {
  name: 'App',
  data() {
    return {
      jsonData: JSON.stringify(defaultData, null, 2),
      apiResult: '',
      apiSuccess: false,
      apiUrl: 'http://localhost:9001/internet/addEquipment',
      contentType: 'json',
      timeout: 5000,
      formFields: [
        { key: 'number', value: '1' },
        { key: 'eq_id', value: '1' }
      ]
    };
  },
  methods: {
    addField() {
      this.formFields.push({ key: '', value: '' });
    },
    removeField(index) {
      this.formFields.splice(index, 1);
    },
    loadPreset(presetName) {
      const preset = presets[presetName];
      if (preset) {
        this.apiUrl = preset.url;
        this.contentType = preset.type;
        if (preset.type === 'json') {
          this.jsonData = JSON.stringify(preset.data, null, 2);
        } else {
          this.formFields = [...preset.data]; // 克隆数组避免引用
        }
      }
    },
    async testApi(method) {
      try {
        // 使指定的请求方法有效
        let requestMethod = method.toLowerCase();
        if (!['get', 'post', 'put', 'delete'].includes(requestMethod)) {
          requestMethod = 'post';
        }
        
        // 设置请求配置
        const config = {
          timeout: this.timeout,
          headers: {}
        };
        
        let requestData;
        
        // 根据内容类型处理数据
        if (this.contentType === 'json') {
          // 解析JSON数据
          requestData = JSON.parse(this.jsonData);
          config.headers['Content-Type'] = 'application/json';
        } else if (this.contentType === 'form') {
          // 处理表单数据
          const params = new URLSearchParams();
          this.formFields.forEach(field => {
            if (field.key && field.value !== undefined) {
              params.append(field.key, field.value);
            }
          });
          
          requestData = params;
          config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        } else if (this.contentType === 'multipart') {
          // 处理多部分表单数据
          const formData = new FormData();
          this.formFields.forEach(field => {
            if (field.key && field.value !== undefined) {
              formData.append(field.key, field.value);
            }
          });
          
          requestData = formData;
          // 不设置Content-Type，让浏览器自动设置带边界的类型
        }
        
        console.log(`正在发送${requestMethod.toUpperCase()}请求到 ${this.apiUrl}`);
        console.log('请求数据:', this.contentType === 'json' ? requestData : Object.fromEntries(requestData));
        console.log('请求头:', config.headers);
        
        // 发送请求
        let response;
        if (requestMethod === 'get') {
          response = await axios.get(this.apiUrl, config);
        } else if (requestMethod === 'post') {
          response = await axios.post(this.apiUrl, requestData, config);
        } else if (requestMethod === 'put') {
          response = await axios.put(this.apiUrl, requestData, config);
        } else if (requestMethod === 'delete') {
          response = await axios.delete(this.apiUrl, { 
            ...config,
            data: requestData
          });
        }
        
        // 处理响应
        this.apiSuccess = true;
        this.apiResult = typeof response.data === 'object' 
          ? JSON.stringify(response.data, null, 2)
          : response.data;
        console.log('API响应成功:', response);
      } catch (error) {
        this.apiSuccess = false;
        
        // 格式化错误信息
        if (error.response) {
          // 请求已发出，服务器响应状态码非2xx
          this.apiResult = JSON.stringify({
            status: error.response.status,
            statusText: error.response.statusText,
            data: error.response.data,
            headers: error.response.headers
          }, null, 2);
          console.error('API响应错误:', error.response);
        } else if (error.request) {
          // 请求已发出，但没有收到响应
          this.apiResult = JSON.stringify({
            message: 'No response received',
            request: error.request
          }, null, 2);
          console.error('没有收到API响应:', error.request);
        } else {
          // 请求设置触发错误
          this.apiResult = JSON.stringify({
            message: error.message,
            stack: error.stack
          }, null, 2);
          console.error('API请求错误:', error.message);
        }
      }
    },
    resetData() {
      if (this.contentType === 'json') {
        this.jsonData = JSON.stringify(defaultData, null, 2);
      } else {
        this.formFields = [{ key: '', value: '' }];
      }
      this.apiResult = '';
    }
  }
};
</script>

<style>
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  background-color: #f5f5f5;
}

.container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

h2 {
  color: #444;
  margin-top: 10px;
  margin-bottom: 15px;
}

.card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.json-input {
  width: 100%;
  font-family: monospace;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.controls {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  gap: 10px;
}

.btn {
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
  transition: background-color 0.3s;
}

.btn.small-btn {
  padding: 4px 8px;
  font-size: 12px;
}

.btn.primary {
  background-color: #4CAF50;
  color: white;
}

.btn.primary:hover {
  background-color: #45a049;
}

.btn.secondary {
  background-color: #2196F3;
  color: white;
}

.btn.secondary:hover {
  background-color: #0b7dda;
}

.btn.reset {
  background-color: #f44336;
  color: white;
}

.btn.reset:hover {
  background-color: #da190b;
}

.btn.danger {
  background-color: #f44336;
  color: white;
}

.btn.preset {
  background-color: #9c27b0;
  color: white;
  margin: 5px;
}

.btn.preset:hover {
  background-color: #7b1fa2;
}

.result {
  margin-top: 20px;
}

.status {
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 4px;
  font-weight: bold;
}

.status.success {
  background-color: #dff0d8;
  color: #3c763d;
}

.status.error {
  background-color: #f2dede;
  color: #a94442;
}

.response {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  overflow-x: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: monospace;
}

.api-config {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.input-group {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.input-group label {
  width: 120px;
  font-weight: bold;
}

.api-input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.timeout-input {
  width: 100px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-fields {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.form-field {
  display: flex;
  gap: 10px;
}

.field-key {
  width: 30%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.field-value {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.preset-section {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
  text-align: center;
}

.preset-buttons {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 10px;
}

@media (max-width: 600px) {
  .form-field {
    flex-direction: column;
  }
  
  .field-key {
    width: 100%;
  }
  
  .controls {
    flex-direction: column;
  }
}
</style> 